<template>
  <div class="labor-management">
    <el-card>
      <div slot="header">
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">发布任务</el-button>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20" class="search-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索任务标题或描述"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :xs="12" :sm="6" :md="4" :lg="4" :xl="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 100%">
              <el-option label="招聘中" value="recruiting" />
              <el-option label="已发布" value="published" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已关闭" value="closed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-col>
          <el-col :xs="12" :sm="6" :md="4" :lg="4" :xl="4">
            <el-select 
              v-model="searchForm.schoolId" 
              placeholder="选择学校" 
              clearable 
              filterable
              :loading="schoolLoading"
              @focus="handleSchoolSelectFocus"
              style="width: 100%"
            >
              <el-option
                v-for="school in schoolOptions"
                :key="school.id"
                :label="school.name"
                :value="school.id"
              />
              <div slot="empty" class="school-select-empty">
                <p>暂无学校数据</p>
                <el-button type="text" @click="refreshSchoolOptions" size="small">
                  <i class="el-icon-refresh"></i> 重新加载
                </el-button>
              </div>
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
              <el-button @click="handleReset" size="small">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 任务列表 -->
      <el-table
        :data="taskList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="50" align="center" />
        <el-table-column prop="jobTitle" label="任务标题" min-width="100" show-overflow-tooltip />
        <el-table-column prop="salary" label="薪资" width="100" align="center">
          <template slot-scope="scope">
            ¥{{ scope.row.salary }}
          </template>
        </el-table-column>
        <el-table-column prop="location" label="工作地点" min-width="60" show-overflow-tooltip />
        <el-table-column prop="publisher" label="发布者" width="100" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyCount" label="申请人数" width="100" align="center" />
        <el-table-column prop="viewCount" label="浏览次数" width="100" align="center" />
        <el-table-column prop="createTime" label="发布时间" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button size="mini" type="info" @click="handleViewApplicants(scope.row)" plain>查看申请信息</el-button>
              <el-button size="mini" type="primary" @click="handleView(scope.row)" plain>查看详情</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)" plain>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 任务详情/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        :model="taskForm"
        :rules="taskRules"
        ref="taskForm"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务标题" prop="title">
              <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资" prop="salary">
              <el-input-number 
                v-model="taskForm.salary" 
                :min="0" 
                :precision="2"
                placeholder="请输入薪资"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="任务描述" prop="description">
          <el-input 
            v-model="taskForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作时长" prop="workHours">
              <el-input-number 
                v-model="taskForm.workHours" 
                :min="1" 
                placeholder="请输入工作时长"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作地点" prop="location">
              <el-input v-model="taskForm.location" placeholder="请输入工作地点" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学校" prop="schoolId">
              <el-select 
                v-model="taskForm.schoolId" 
                placeholder="请选择学校" 
                filterable
                :loading="schoolLoading"
                @focus="handleSchoolSelectFocus"
                style="width: 100%"
              >
                <el-option
                  v-for="school in schoolOptions"
                  :key="school.id"
                  :label="school.name"
                  :value="school.id"
                />
                <div slot="empty" class="school-select-empty">
                  <p>暂无学校数据</p>
                  <el-button type="text" @click="refreshSchoolOptions" size="small">
                    <i class="el-icon-refresh"></i> 重新加载
                  </el-button>
                </div>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="taskForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="草稿" value="draft" />
                <el-option label="已发布" value="published" />
                <el-option label="进行中" value="in_progress" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      width="900px"
      :show-close="false"
      class="task-detail-dialog"
    >
      <div slot="title" class="dialog-header">
        <div class="header-content">
          <div class="header-info">
            <h3 class="task-title">{{ currentTask ? currentTask.jobTitle || currentTask.title : '' }}</h3>
            <div class="task-meta">
              <el-tag 
                v-if="currentTask"
                :type="getStatusType(currentTask.status)" 
                size="medium"
                class="status-tag"
              >
                {{ getStatusName(currentTask.status) }}
              </el-tag>
              <span class="task-id">ID: {{ currentTask ? currentTask.id : '' }}</span>
        </div>
        </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="small" 
              icon="el-icon-edit"
              @click="handleEditFromDetail"
              plain
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              icon="el-icon-user"
              @click="handleViewApplicantsFromDetail"
              plain
            >
              申请人
            </el-button>
            <el-button 
              size="small" 
              icon="el-icon-close"
              @click="detailDialogVisible = false"
              circle
            />
        </div>
        </div>
        </div>

      <div v-if="currentTask" class="task-detail-content">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-info"></i>
            基本信息
          </h4>
          <div class="detail-grid">
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">薪资待遇</label>
                  <div class="field-value salary-value">
                    <i class="el-icon-money"></i>
                    ¥{{ currentTask.salary }}
        </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">工作时长</label>
                  <div class="field-value">
                    <i class="el-icon-time"></i>
                    {{ currentTask.workHours || '未指定' }}小时
                  </div>
                </div>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">工作地点</label>
                  <div class="field-value">
                    <i class="el-icon-location-outline"></i>
                    {{ currentTask.location || '未指定' }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">工作类型</label>
                  <div class="field-value">
                    <i class="el-icon-suitcase"></i>
                    {{ getWorkTypeName(currentTask.workType) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 任务描述 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-document"></i>
            任务描述
          </h4>
          <div class="description-content">
            <p class="description-text">{{ currentTask.description || '暂无描述' }}</p>
          </div>
        </div>

        <!-- 发布信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-user-solid"></i>
            发布信息
          </h4>
          <div class="detail-grid">
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">发布者</label>
                  <div class="field-value">
                    <i class="el-icon-user"></i>
                    {{ currentTask.publisher || '未知' }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">发布时间</label>
                  <div class="field-value">
                    <i class="el-icon-date"></i>
                    {{ formatDate(currentTask.createTime) }}
                  </div>
                </div>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">学校</label>
                  <div class="field-value">
                    <i class="el-icon-school"></i>
                    {{ currentTask.schoolName || '未指定' }}
                  </div>
                </div>
              </div>
              <div class="detail-col">
                <div class="detail-field">
                  <label class="field-label">联系方式</label>
                  <div class="field-value">
                    <i class="el-icon-phone"></i>
                    {{ currentTask.contactPhone || '见申请人列表' }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <i class="el-icon-data-analysis"></i>
            统计信息
          </h4>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-icon apply-icon">
                <i class="el-icon-user-solid"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ currentTask.applyCount || 0 }}</div>
                <div class="stat-label">申请人数</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon view-icon">
                <i class="el-icon-view"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ currentTask.viewCount || 0 }}</div>
                <div class="stat-label">浏览次数</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon status-icon">
                <i class="el-icon-circle-check"></i>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ getStatusProgress(currentTask.status) }}%</div>
                <div class="stat-label">完成进度</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作历史 -->
        <div class="detail-section" v-if="currentTask.updateTime">
          <h4 class="section-title">
            <i class="el-icon-time"></i>
            操作历史
          </h4>
          <div class="timeline-content">
            <el-timeline>
              <el-timeline-item 
                timestamp="创建时间" 
                :color="'#67c23a'"
                icon="el-icon-plus"
              >
                {{ formatDate(currentTask.createTime) }} - 任务创建
              </el-timeline-item>
              <el-timeline-item 
                v-if="currentTask.updateTime && currentTask.updateTime !== currentTask.createTime"
                timestamp="最后更新" 
                :color="'#409eff'"
                icon="el-icon-edit"
              >
                {{ formatDate(currentTask.updateTime) }} - 任务更新
              </el-timeline-item>
              <el-timeline-item 
                timestamp="当前状态" 
                :color="getStatusColor(currentTask.status)"
                icon="el-icon-circle-check"
              >
              {{ getStatusName(currentTask.status) }}
              </el-timeline-item>
            </el-timeline>
        </div>
        </div>
        </div>

      <div slot="footer" class="dialog-footer">
        <div class="footer-stats">
          <span class="footer-text">创建于 {{ formatDate(currentTask ? currentTask.createTime : '') }}</span>
        </div>
        <div class="footer-actions">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleViewApplicantsFromDetail" icon="el-icon-user">
            查看申请人 ({{ currentTask ? (currentTask.applyCount || 0) : 0 }})
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 申请人信息对话框 -->
    <el-dialog
      title="申请人信息"
      :visible.sync="applicantsDialogVisible"
      width="900px"
    >
      <div v-if="currentTask" class="applicants-header">
        <div class="header-content">
          <div>
            <h4>{{ currentTask.jobTitle || currentTask.title }} - 申请人列表</h4>
            <p>共 {{ applicantsList.length }} 人申请</p>
          </div>
          <el-button 
            type="primary" 
            size="small" 
            @click="retryLoadApplicants"
            :loading="applicantsLoading"
            icon="el-icon-refresh"
          >
            刷新数据
          </el-button>
        </div>
      </div>
      
      <!-- 空状态显示 -->
      <div v-if="!applicantsLoading && applicantsList.length === 0" class="applicants-empty">
        <el-empty description="暂无申请人数据">
          <el-button type="primary" @click="retryLoadApplicants">重新加载</el-button>
        </el-empty>
      </div>
      
      <el-table
        v-if="applicantsList.length > 0"
        :data="applicantsList"
        v-loading="applicantsLoading"
        stripe
        style="width: 100%"
      >
        <el-table-column label="姓名" width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.applicantNickname || '未提供' }}
          </template>
        </el-table-column>
        <el-table-column label="联系电话" width="130">
          <template slot-scope="scope">
            {{ scope.row.applicantPhone || '未提供' }}
          </template>
        </el-table-column>
        <el-table-column label="联系方式" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="contact-info">
              <div v-if="scope.row.applicantQq" class="contact-item">
                <span class="contact-label">QQ:</span> {{ scope.row.applicantQq }}
              </div>
              <div v-if="scope.row.applicantWechat" class="contact-item">
                <span class="contact-label">微信:</span> {{ scope.row.applicantWechat }}
              </div>
              <div v-if="!scope.row.applicantQq && !scope.row.applicantWechat" class="contact-item">
                暂无
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getApplicantStatusType(scope.row.status)" size="small">
              {{ getApplicantStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="申请说明" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.applicationNote || '无说明' }}
          </template>
        </el-table-column>
        <el-table-column prop="applicationTime" label="申请时间" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.applicationTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.status === 'pending'"
              size="mini" 
              type="success" 
              @click="handleApproveApplicant(scope.row)"
              plain
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'"
              size="mini" 
              type="danger" 
              @click="handleRejectApplicant(scope.row)"
              plain
            >
              拒绝
            </el-button>
            <span v-if="scope.row.status !== 'pending'" class="status-text">
              {{ getApplicantStatusName(scope.row.status) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "LaborManagement",
  data() {
    return {
      loading: false,
      submitLoading: false,
      taskList: [],
      schoolOptions: [],
      schoolLoading: false,
      searchForm: {
        keyword: "",
        status: "",
        schoolId: ""
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      applicantsDialogVisible: false,
      dialogTitle: "",
      isEdit: false,
      currentTask: null,
      applicantsList: [],
      applicantsLoading: false,
      taskForm: {
        id: null,
        title: "",
        description: "",
        salary: 0,
        workHours: 1,
        location: "",
        schoolId: "",
        status: "draft"
      },
      taskRules: {
        title: [
          { required: true, message: "请输入任务标题", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入任务描述", trigger: "blur" }
        ],
        salary: [
          { required: true, message: "请输入薪资", trigger: "blur" }
        ],
        workHours: [
          { required: true, message: "请输入工作时长", trigger: "blur" }
        ],
        location: [
          { required: true, message: "请输入工作地点", trigger: "blur" }
        ],
        schoolId: [
          { required: true, message: "请选择学校", trigger: "change" }
        ]
      }
    }
  },
  async created() {
    await this.loadSchoolOptions()
    await this.loadTaskList()
  },
  methods: {
    async loadSchoolOptions(showMessage = false) {
      this.schoolLoading = true
      try {
        const response = await this.$http.get("/admin/schools/options")
        if (response.data.code === 200) {
          this.schoolOptions = response.data.data || []
          if (showMessage && this.schoolOptions.length > 0) {
            this.$message.success(`成功加载 ${this.schoolOptions.length} 所学校`)
          }
        } else {
          throw new Error(response.data.message || '获取学校列表失败')
        }
      } catch (error) {
        console.error("加载学校选项失败:", error)
        if (showMessage) {
          this.$message.error('加载学校列表失败，使用默认数据')
        }
        // 使用模拟数据
        this.schoolOptions = [
          { id: 1, name: "北京大学" },
          { id: 2, name: "清华大学" },
          { id: 3, name: "复旦大学" },
          { id: 4, name: "上海交通大学" },
          { id: 5, name: "中山大学" },
          { id: 6, name: "华中科技大学" },
          { id: 7, name: "西安交通大学" },
          { id: 8, name: "南京大学" }
        ]
      } finally {
        this.schoolLoading = false
      }
    },

    // 刷新学校选项
    async refreshSchoolOptions() {
      await this.loadSchoolOptions(true)
    },

    // 检查学校选项是否需要重新加载
    checkAndReloadSchools() {
      if (this.schoolOptions.length === 0 && !this.schoolLoading) {
        this.loadSchoolOptions()
      }
    },

    // 处理学校选择器焦点事件，确保有数据
    handleSchoolSelectFocus() {
      this.checkAndReloadSchools()
    },

    async loadTaskList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await this.$http.get("/admin/labors", { params })
        if (response.data.code === 200) {
          this.taskList = response.data.data.records || []
          this.pagination.total = response.data.data.total || 0
        }
      } catch (error) {
        console.error("加载任务列表失败:", error)
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },

    loadMockData() {
      this.taskList = [
        {
          id: 1,
          title: "图书馆兼职工作",
          description: "负责图书馆书籍整理、借还书服务等工作",
          salary: 25,
          workHours: 4,
          location: "图书馆一楼",
          schoolName: "北京大学",
          status: "published",
          applicantCount: 15,
          createdAt: "2025-09-20T10:00:00"
        },
        {
          id: 2,
          title: "食堂服务员",
          description: "负责食堂窗口服务、清洁卫生等工作",
          salary: 20,
          workHours: 6,
          location: "学生食堂",
          schoolName: "清华大学",
          status: "in_progress",
          applicantCount: 8,
          createdAt: "2025-09-19T14:30:00"
        },
        {
          id: 3,
          title: "实验室助手",
          description: "协助实验室老师进行实验准备和器材整理",
          salary: 30,
          workHours: 3,
          location: "化学实验室",
          schoolName: "复旦大学",
          status: "completed",
          applicantCount: 12,
          createdAt: "2025-09-18T09:15:00"
        }
      ]
      this.pagination.total = 3
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadTaskList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        status: "",
        schoolId: ""
      }
      this.pagination.currentPage = 1
      this.loadTaskList()
    },

    handleAdd() {
      this.dialogTitle = "发布兼职任务"
      this.isEdit = false
      this.taskForm = {
        id: null,
        title: "",
        description: "",
        salary: 0,
        workHours: 1,
        location: "",
        schoolId: "",
        status: "draft"
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = "编辑任务"
      this.isEdit = true
      this.taskForm = {
        id: row.id,
        title: row.title,
        description: row.description,
        salary: row.salary,
        workHours: row.workHours,
        location: row.location,
        schoolId: row.schoolId,
        status: row.status
      }
      this.dialogVisible = true
    },

    handleView(row) {
      this.currentTask = row
      this.detailDialogVisible = true
    },

    async handleViewApplicants(row) {
      this.currentTask = row
      this.applicantsDialogVisible = true
      await this.loadApplicants(row.id)
    },

    async loadApplicants(laborId, showRetry = false) {
      this.applicantsLoading = true
      this.applicantsList = [] // 清空现有数据
      
      try {
        // 尝试使用管理员端点，如果不存在则使用普通端点
        let response;
        try {
          // 首先尝试管理员专用端点
          response = await this.$http.get(`/admin/labors/${laborId}/applicants`);
        } catch (adminError) {
          // 如果管理员端点不存在，尝试使用普通端点
          if (adminError.response && adminError.response.status === 404) {
            console.warn('管理员申请人端点不存在，使用普通端点');
            response = await this.$http.get(`/labor/applications/${laborId}`);
          } else {
            throw adminError;
          }
        }
        
        if (response.data.code === 200) {
          this.applicantsList = response.data.data || []
          
          // 调试信息：打印申请人数据结构
          if (this.applicantsList.length > 0) {
            console.log('申请人数据结构:', this.applicantsList[0])
          }
          
          if (this.applicantsList.length === 0) {
            this.$message.info('该任务暂无申请人')
          } else if (showRetry) {
            this.$message.success(`成功加载 ${this.applicantsList.length} 条申请信息`)
          }
        } else {
          const errorMsg = response.data.message || '获取申请人信息失败'
          this.$message.error(errorMsg)
          throw new Error(errorMsg)
        }
      } catch (error) {
        console.error('获取申请人信息失败:', error)
        
        // 根据错误类型显示不同的错误信息
        let errorMessage = '获取申请人信息失败'
        if (error.response) {
          // 服务器响应错误
          if (error.response.status === 404) {
            errorMessage = '任务不存在或已被删除'
          } else if (error.response.status === 403) {
            errorMessage = '没有权限查看申请信息'
          } else if (error.response.status >= 500) {
            errorMessage = '服务器内部错误，请稍后重试'
          }
        } else if (error.request) {
          // 网络错误
          errorMessage = '网络连接失败，请检查网络后重试'
        }
        
        this.$message.error(errorMessage)
        this.applicantsList = []
      } finally {
        this.applicantsLoading = false
      }
    },

    // 重新加载申请人信息
    async retryLoadApplicants() {
      if (this.currentTask && this.currentTask.id) {
        await this.loadApplicants(this.currentTask.id, true)
      }
    },


    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该任务吗？删除后将不再显示在列表中！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 使用逻辑删除，调用PUT请求更新删除状态
        const response = await this.$http.put(`/admin/labors/${row.id}/delete`)
        
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.loadTaskList()
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除任务失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSubmit() {
      try {
        await this.$refs.taskForm.validate()
        this.submitLoading = true

        const url = this.isEdit ? `/admin/labors/${this.taskForm.id}` : '/admin/labors'
        const method = this.isEdit ? 'put' : 'post'
        
        const response = await this.$http[method](url, this.taskForm)
        
        if (response.data.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '发布成功')
          this.dialogVisible = false
          this.loadTaskList()
        } else {
          this.$message.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('操作失败')
      } finally {
        this.submitLoading = false
      }
    },

    handleDialogClose() {
      this.$refs.taskForm.resetFields()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadTaskList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTaskList()
    },

    getStatusType(status) {
      const statusMap = {
        draft: "info",
        recruiting: "success",
        published: "success",
        in_progress: "warning",
        completed: "success",
        closed: "danger",
        cancelled: "danger"
      }
      return statusMap[status] || "info"
    },

    getStatusName(status) {
      const statusMap = {
        draft: "草稿",
        recruiting: "招聘中",
        published: "已发布",
        in_progress: "进行中",
        completed: "已完成",
        closed: "已关闭",
        cancelled: "已取消"
      }
      return statusMap[status] || "未知"
    },

    getWorkTypeName(workType) {
      const workTypeMap = {
        "one-off": "一次性",
        "part-time": "兼职",
        "full-time": "全职"
      }
      return workTypeMap[workType] || workType
    },

    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    },

    // 从详情页面编辑任务
    handleEditFromDetail() {
      this.detailDialogVisible = false
      this.handleEdit(this.currentTask)
    },

    // 从详情页面查看申请人
    handleViewApplicantsFromDetail() {
      this.detailDialogVisible = false
      this.handleViewApplicants(this.currentTask)
    },

    // 获取状态对应的进度百分比
    getStatusProgress(status) {
      const progressMap = {
        draft: 0,
        published: 25,
        recruiting: 25,
        in_progress: 75,
        completed: 100,
        closed: 100,
        cancelled: 0
      }
      return progressMap[status] || 0
    },

    // 获取状态对应的颜色
    getStatusColor(status) {
      const colorMap = {
        draft: '#909399',
        recruiting: '#67c23a',
        published: '#67c23a',
        in_progress: '#e6a23c',
        completed: '#67c23a',
        closed: '#f56c6c',
        cancelled: '#f56c6c'
      }
      return colorMap[status] || '#909399'
    },

    getApplicantStatusType(status) {
      const statusMap = {
        pending: "warning",
        approved: "success", 
        rejected: "danger"
      }
      return statusMap[status] || "info"
    },

    getApplicantStatusName(status) {
      const statusMap = {
        pending: "待审核",
        approved: "已通过",
        rejected: "已拒绝"
      }
      return statusMap[status] || "未知"
    },

    async handleApproveApplicant(applicant) {
      try {
        await this.$confirm(`确定要通过 ${applicant.applicantNickname} 的申请吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        // 使用劳务审核端点
        const response = await this.$http.post('/labor/review', {
          applicationId: applicant.id,
          status: 'approved',
          reviewNote: '管理员审核通过'
        })
        
        if (response.data.code === 200) {
          this.$message.success(`已通过 ${applicant.applicantNickname} 的申请`)
          // 重新加载申请人列表以获取最新状态
          await this.loadApplicants(this.currentTask.id)
        } else {
          this.$message.error(response.data.message || '审核操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审核申请失败:', error)
          let errorMessage = '审核操作失败'
          if (error.response && error.response.status === 404) {
            errorMessage = '申请记录不存在'
          } else if (error.response && error.response.status === 403) {
            errorMessage = '没有权限执行此操作'
          }
          this.$message.error(errorMessage)
        }
      }
    },

    async handleRejectApplicant(applicant) {
      try {
        await this.$confirm(`确定要拒绝 ${applicant.applicantNickname} 的申请吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 使用劳务审核端点
        const response = await this.$http.post('/labor/review', {
          applicationId: applicant.id,
          status: 'rejected',
          reviewNote: '管理员审核拒绝'
        })
        
        if (response.data.code === 200) {
          this.$message.success(`已拒绝 ${applicant.applicantNickname} 的申请`)
          // 重新加载申请人列表以获取最新状态
          await this.loadApplicants(this.currentTask.id)
        } else {
          this.$message.error(response.data.message || '拒绝操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝申请失败:', error)
          let errorMessage = '拒绝操作失败'
          if (error.response && error.response.status === 404) {
            errorMessage = '申请记录不存在'
          } else if (error.response && error.response.status === 403) {
            errorMessage = '没有权限执行此操作'
          }
          this.$message.error(errorMessage)
        }
      }
    }
  }
}
</script>

<style scoped>
.labor-management {
  padding: 0;
  width: 100%;
  min-height: calc(100vh - 120px);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.add-button {
  margin-left: auto;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
  padding: 0 10px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}

.action-buttons .el-button {
  margin: 0;
  padding: 5px 8px;
  font-size: 12px;
}

.task-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.detail-item p {
  margin: 5px 0;
  line-height: 1.6;
}

/* 任务详情对话框样式 */
.task-detail-dialog {
  .el-dialog__header {
    padding: 0;
    border-bottom: 1px solid #ebeef5;
  }

  .el-dialog__body {
    padding: 0;
    max-height: 70vh;
    overflow-y: auto;
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #fafafa;
  }
}

.dialog-header {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.header-info {
  flex: 1;
}

.task-title {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 600;
  line-height: 1.3;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-tag {
  font-weight: 500;
}

.task-id {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-actions .el-button {
  color: white;
  border-color: rgba(255, 255, 255, 0.3);
}

.header-actions .el-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.5);
}

.task-detail-content {
  padding: 0;
}

.detail-section {
  padding: 20px;
  border-bottom: 1px solid #f0f2f5;
}

.detail-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: #409eff;
}

.detail-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  gap: 20px;
}

.detail-col {
  flex: 1;
}

.detail-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-label {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.field-value {
  font-size: 14px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #e4e7ed;
}

.field-value i {
  color: #909399;
  font-size: 16px;
}

.salary-value {
  border-left-color: #67c23a;
  background-color: #f0f9ff;
  color: #16a34a;
  font-weight: 600;
}

.salary-value i {
  color: #16a34a;
}

.description-content {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border-left: 4px solid #409eff;
}

.description-text {
  margin: 0;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.stat-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
}

.apply-icon {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.view-icon {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.status-icon {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.timeline-content {
  padding-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-stats {
  flex: 1;
}

.footer-text {
  color: #909399;
  font-size: 13px;
}

.footer-actions {
  display: flex;
  gap: 8px;
}

/* 申请人信息对话框样式 */
.applicants-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.applicants-header .header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.applicants-header h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.applicants-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.applicants-empty {
  text-align: center;
  padding: 40px 20px;
}

/* 联系方式样式 */
.contact-info {
  line-height: 1.4;
}

.contact-item {
  margin-bottom: 4px;
  font-size: 12px;
}

.contact-item:last-child {
  margin-bottom: 0;
}

.contact-label {
  font-weight: 500;
  color: #606266;
  margin-right: 4px;
}

.status-text {
  color: #909399;
  font-size: 12px;
}

/* 学校选择器空状态样式 */
.school-select-empty {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.school-select-empty p {
  margin: 0 0 10px 0;
  font-size: 14px;
}

.school-select-empty .el-button {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin: 1px 0;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .add-button {
    margin-left: 0;
    width: 100%;
  }
  
  .search-area {
    padding: 15px;
  }
  
  .search-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .search-buttons {
    justify-content: center;
    width: 100%;
  }
  
  .pagination-area {
    text-align: center;
  }
  
  .action-buttons {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .action-buttons .el-button {
    flex: 1;
    min-width: 60px;
  }

  /* 申请人对话框响应式 */
  .applicants-header .header-content {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  /* 任务详情对话框响应式 */
  .task-detail-dialog {
    width: 95% !important;
    margin: 0 auto;
  }

  .header-content {
    flex-direction: column;
    gap: 15px;
  }

  .header-actions {
    align-self: stretch;
    justify-content: space-between;
  }

  .detail-row {
    flex-direction: column;
    gap: 12px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .footer-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .labor-management {
    padding: 0 5px;
  }
  
  .search-area {
    padding: 10px;
    margin-bottom: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin: 2px 0;
  }
}
</style>
